import * as React from 'react';
import PropTypes from 'prop-types';
import { Form, Field, DatePicker, Select, Balloon } from '@teamix/ui';
import { YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import dayjs from 'dayjs';
import MemberTrigger from 'components/memberTrigger';
import Popup from 'components/popup';
// import PathEllipsis from 'components/pathEllipsis';
import utils from 'utils';
import '../index.scss';
import intl from '../../../../../../../../../locale';
const { RangePicker } = DatePicker;
const { Tooltip } = Balloon;
const { organization } = window.FORCE;

const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    fixedSpan: 12,
  },
};

const allType = ['DEL_REPO', 'ORG_PUBLIC_REPO', 'DEL_GROUP', 'ORG_PUBLIC_GROUP'].join(',');
const typeDataSource = [
  {
    value: allType,
    label: intl.get({
      id: 'code-assets.securityNotify.containers.filterForm.AllOperations',
      defaultMessage: '所有操作',
    }),
  },
  {
    value: 'DEL_REPO',
    label: intl.get({
      id: 'code-assets.securityNotify.containers.filterForm.DeleteADatabase',
      defaultMessage: '库删除',
    }),
  },
  // { value: 'TRANSFER_REPO', label: '库转移' },
  {
    value: 'ORG_PUBLIC_REPO',
    label: intl.get({
      id: 'code-assets.securityNotify.containers.filterForm.PublicLibrary',
      defaultMessage: '库公开',
    }),
  },
  {
    value: 'DEL_GROUP',
    label: intl.get({
      id: 'code-assets.securityNotify.containers.filterForm.GroupDeletion',
      defaultMessage: '组删除',
    }),
  },
  {
    value: 'ORG_PUBLIC_GROUP',
    label: intl.get({
      id: 'code-assets.securityNotify.containers.filterForm.GroupPublic',
      defaultMessage: '组公开',
    }),
  },
];

const maxTagPlaceholder = (selectedValues, totalValues) => {
  const trigger = <span>{`${selectedValues.length}/${totalValues.length}`}</span>;
  const labels = selectedValues.map((obj) => obj.label);
  return <Tooltip trigger={trigger}>{labels.join(', ')}</Tooltip>;
};
const NO_GROUP_TEXT = intl.get({
  id: 'code-assets.securityNotify.containers.filterForm.DoNotSelectACode',
  defaultMessage: '不选择代码组',
});

export default class FilterForm extends React.Component {
  static propTypes = {
    pageSize: PropTypes.string,
    getParamsData: PropTypes.func,
  };

  constructor(props) {
    super(props);
    this.field = new Field(this, { autoUnmount: false });
    this.state = {
      operatorData: [],
    };
  }

  componentDidMount() {
    this.onGroupSearch();
    this.onProjectSearch();
    this.setFormInit();
    document.body.addEventListener('click', this.onDatePickerClear);
  }

  componentWillUnmount() {
    document.body.removeEventListener('click', this.onDatePickerClear);
  }

  onDatePickerClear = (e) => {
    try {
      if (e.target.classList.contains('yx-icon-delete-filling')) {
        this.field.setValues({
          start_time: null,
          end_time: null,
          range: null,
        });
        this.getFormDataAndDoSearch();
      }
    } catch (error) {
      //
    }
  };

  // 搜索代码库得到的结果
  onProjectSearch = (search) => {
    const formData = this.field.getValues();
    if (formData.group_id) {
      formData.group_id = formData.group_id.join(',');
    }
    this.props.getProjectData(formData.group_id, search);
  };

  onGroupSearch = (search) => {
    this.props.getGroupData(search);
  };

  setFormInit = () => {
    this.field.setValues({
      operator_id: null,
      type: allType,
      project_id: null,
      group_id: null,
      start_time: null,
      end_time: null,
      range: null,
    });

    this.setState({
      operatorData: [],
    });
  };

  setProjectFormInit = () => {
    this.field.setValues({
      project_id: null,
    });
  };

  // 获取表单数据并触发查询
  getFormDataAndDoSearch = () => {
    const { pageSize } = this.props;
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        if (formData.tb_user_ids) {
          formData.tb_user_ids = formData.tb_user_ids.join(',');
        }
        if (formData.project_id) {
          formData.project_id = formData.project_id.join(',');
        }
        if (formData.group_id) {
          formData.group_id = formData.group_id.join(',');
        }
        if (formData.range) {
          formData.start_time = dayjs(formData.range[0]).format('YYYY-MM-DD');
          formData.end_time = dayjs(formData.range[1]).format('YYYY-MM-DD');
        }
        delete formData.range;
        this.props.getParamsData(1, pageSize, formData);
      }
    });
  };

  onRangePickerOk = () => {
    this.getFormDataAndDoSearch();
  };

  onResetClick = () => {
    this.setFormInit();
    this.getFormDataAndDoSearch();
  };

  onMemberChange = (value) => {
    this.setState({
      operatorData: value,
    });

    this.field.setValue(
      'tb_user_ids',
      value.map((item) => item._userId),
    );
    this.getFormDataAndDoSearch();
  };

  onTypeChange = (value) => {
    this.field.setValue('type', value);
    this.getFormDataAndDoSearch();
  };

  onRepoChange = (value) => {
    this.field.setValue(
      'project_id',
      value.map((item) => item),
    );
    if (value.length === 0) {
      this.onProjectSearch();
    }
    this.getFormDataAndDoSearch();
  };

  onGroupChange = (value) => {
    this.field.setValue(
      'group_id',
      value.map((item) => item),
    );
    if (value.length === 0) {
      this.onGroupSearch();
    }
    this.setProjectFormInit();
    this.getFormDataAndDoSearch();
    this.onProjectSearch();
  };

  getGroupLabel = (path, id) => {
    if (Number(id) === Number(organization.namespace_id)) {
      return NO_GROUP_TEXT;
    } else {
      return path.includes('/') ? utils.getGroupPath(path) : path;
    }
  };

  getGroupOptions = () => {
    const { groups } = this.props;

    const arr = [
      {
        label: intl.get({
          id: 'code-assets.securityNotify.containers.filterForm.LastUpdated',
          defaultMessage: '最近更新',
        }),
        children: [],
      },
    ];

    groups.forEach((p) => {
      const label = this.getGroupLabel(p.path_with_namespace, p.id);
      if (label === NO_GROUP_TEXT) {
        arr.unshift({
          value: p.id,
          label,
        });
      } else {
        const index = arr.findIndex(
          (item) =>
            item.label ===
            intl.get({
              id: 'code-assets.securityNotify.containers.filterForm.LastUpdated',
              defaultMessage: '最近更新',
            }),
        );
        arr[index].children.push({
          value: p.id,
          label,
        });
      }
    });
    return arr;
  };

  render() {
    const { field } = this;
    const { init } = field;
    return (
      <Popup
        size="large"
        trigger={<ButtonIcon name="filter-line" />}
        triggerType="click"
        followTrigger
        placement="br"
        footer={
          <Form.Item style={{ marginBottom: 0 }}>
            <Form.Reset
              text
              type="primary"
              style={{ border: 0 }}
              onClick={this.onResetClick}
              toDefault
            >
              <YunxiaoIcon type="delete-line" />
              {intl.get({
                id: 'code-assets.securityNotify.containers.filterForm.ClearAllFilterConditions',
                defaultMessage: '清除所有筛选条件',
              })}
            </Form.Reset>
          </Form.Item>
        }
      >
        <Form {...formItemLayout} labelTextAlign="left" field={field}>
          <Form.Item
            label={intl.get({
              id: 'code-assets.securityNotify.containers.filterForm.Operator',
              defaultMessage: '操作人',
            })}
          >
            <div
              ref={(o) => {
                this.container = o;
              }}
            >
              <MemberTrigger
                onChange={this.onMemberChange}
                value={this.state.operatorData}
                container={() => this.container}
                multiple
                isInviteUrl
              />
            </div>
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.securityNotify.containers.filterForm.OperationDate',
              defaultMessage: '操作日期',
            })}
          >
            <RangePicker
              {...init('range')}
              followTrigger
              popupAlign="tr br"
              onOk={this.onRangePickerOk}
            />
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.securityNotify.containers.filterForm.Operation',
              defaultMessage: '操作',
            })}
          >
            <Select
              mode="single"
              followTrigger
              dataSource={typeDataSource}
              {...init('type')}
              onChange={this.onTypeChange}
            />
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.securityNotify.containers.filterForm.CodeGroup',
              defaultMessage: '代码组',
            })}
          >
            <Select
              {...init('group_id')}
              mode="multiple"
              showSearch
              followTrigger
              maxTagCount={4}
              placeholder={intl.get({
                id: 'code-assets.securityNotify.containers.filterForm.EnterACodeGroupName',
                defaultMessage: '请输入代码组名以搜索',
              })}
              dataSource={this.getGroupOptions()}
              onSearch={this.onGroupSearch}
              onChange={this.onGroupChange}
              maxTagPlaceholder={maxTagPlaceholder}
            />
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.securityNotify.containers.filterForm.CodeBase',
              defaultMessage: '代码库',
            })}
            style={{ marginBottom: 0 }}
          >
            <Select
              {...init('project_id')}
              mode="multiple"
              showSearch
              followTrigger
              maxTagCount={4}
              placeholder={intl.get({
                id: 'code-assets.src.utils.locale.EnterACodeLibraryName.1',
                defaultMessage: '请输入代码库名以搜索',
              })}
              dataSource={[
                {
                  label: intl.get({
                    id: 'code-assets.securityNotify.containers.filterForm.LastUpdated',
                    defaultMessage: '最近更新',
                  }),
                  children: this.props.projects.map((p) => ({
                    value: p.id,
                    label: p.path_with_namespace.includes('/')
                      ? utils.getGroupPath(p.path_with_namespace)
                      : p.path_with_namespace,
                  })),
                },
              ]}
              onSearch={this.onProjectSearch}
              onChange={this.onRepoChange}
              maxTagPlaceholder={maxTagPlaceholder}
            />
          </Form.Item>
        </Form>
      </Popup>
    );
  }
}
